<!--
 * @Author: zhang00001 774004514@qq.com
 * @Date: 2024-06-17 10:18:04
 * @LastEditors: yansheng 610363806@qq.com
 * @LastEditTime: 2024-07-28 00:21:29
 * @FilePath: \vue-admin\src\pages\active\ActivityForm.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-drawer
      :title="formData.raffle_id ? '编辑' : '新增'"
      placement="right"
      :maskClosable="false"
      :keyboard="false"
      :closable="true"
      width="800"
      v-model:open="showAddDialog"
    >
      <a-form
        ref="formRef"
        :rules="rules"
        :model="formData"
        label-position="top"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item
          label="奖品名称"
          required
          name="prize_name"
        >
          <a-input v-model:value="formData.prize_name"></a-input>
        </a-form-item>
        <a-form-item
          label="奖品图片"
          required
          name="prize_image"
        >
          <ImageUpload
            ref="uploadRef"
            :limit="1"
            :fileSize="1"
            v-model:modelValue="formData.prize_image"
          ></ImageUpload>
        </a-form-item>
        <a-form-item
          label="库存"
          required
          name="stock"
        >
          <a-input-number
            id="inputNumber"
            v-model:value="formData.stock"
            :min="0"
            :max="1000000"
          />
        </a-form-item>
        <a-form-item
          label="中奖概率"
          required
          name="probability"
        >
          <!--  -->
          <a-input-number
            id="inputNumber"
            v-model:value="formData.probability"
            :min="0.01"
            :max="maxCanUse"
            addon-after="%"
          />
          <div
            class="tip"
            style="color: rgb(245, 108, 108)"
          >
            已创建{{ paginationTotal }}条数据，共需8条奖品数据，所有中奖概率之和不得超过100，当前可输入最大不能超过{{
              maxCanUse
            }}
          </div>
        </a-form-item>
        <a-form-item
          label="奖品介绍"
          required
          name="introduce"
        >
          <Editor
            v-model:modelValue="formData.introduce"
            :min-height="192"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="handleCancel">取消</a-button>
          <a-button
            style="margin-left: 20px"
            @click="previewEditDialog"
          >
            预览奖品介绍
          </a-button>

          <!-- :loading="loading" -->
          <a-button
            type="primary"
            style="margin-left: 20px"
            @click="handleSubmit"
          >
            确认
          </a-button>
        </a-form-item>
      </a-form>
      <previewEditor ref="previewEditorEle"></previewEditor>
    </a-drawer>
  </div>
</template>

<script setup>
  import { extractImageUrls, deleteMultiples } from '@/utils/power.js'
  import previewEditor from '@/components/previewEditor.vue'
  import { raffleAdd, raffleUpdate, adminDelTag } from '@/api/index.js'
  import { ref, defineEmits, defineExpose, defineProps, toRefs, nextTick } from 'vue'
  import { message } from 'ant-design-vue'
  import Collect from 'collect.js'
  const emits = defineEmits(['success', 'close'])
  const props = defineProps({
    // showAddDialog: {
    //   type: Boolean,
    //   default: false
    // }
  })
  const showAddDialog = ref(false)
  const loading = ref(false)
  const formRef = ref()
  const rules = {
    title: [
      {
        required: true,
        message: '请输入奖品名称',
        trigger: 'change'
      },
      {
        min: 2,
        max: 50,
        message: '长度2-50字',
        trigger: 'blur'
      }
    ],
    image: [
      {
        required: true,
        message: '请上传奖品图片',
        trigger: 'change'
      }
    ],
    stock: [
      {
        required: true,
        message: '请输入库存',
        trigger: 'blur'
      }
    ],
    probability: [
      {
        required: true,
        message: '请输入中奖概率',
        trigger: 'blur'
      }
    ],
    introduce: [
      {
        required: true,
        message: '请输入奖品介绍',
        trigger: 'blur'
      }
    ]
  }
  // const { showAddDialog } = toRefs(props)
  const formData = ref({
    // raffleId:null,
    prize_name: '',
    prize_image: '',
    stock: '',
    probability: '',
    introduce: ''
  })
  const previewEditorEle = ref(null)
  const previewEditDialog = () => {
    previewEditorEle.value.init(formData.value.introduce)
  }
  const uploadVisible = ref(false)
  const handleSubmit = () => {
    formRef.value.validate().then(() => {
      loading.value = true
      let http = formData.value.raffle_id ? raffleUpdate : raffleAdd
      let params

      if (formData.value.raffle_id) {
        const collection = Collect(formData.value)

        const diff = collection.diffAssoc(dateRow.value)
      
        if (diff.items.introduce) {
          const imageUrls = extractImageUrls(diff.items.introduce)

          const delArrImages = Collect(richImage.value).diff(imageUrls).all()
          // 新增的图
          const newArrImages = Collect(imageUrls).diff(richImage.value).all()
          if (newArrImages.length > 0) {
            adminDelTag({ img: newArrImages })
          }

          if (delArrImages && delArrImages.length > 0) {
            deleteMultiples(delArrImages)
          }
        }
        params = {
          raffle_id: formData.value.raffle_id,
          ...diff.all()
        }
        if (Object.values(params).length == 1) {
        message.error('暂未修改')
        return
      }
      } else {
        params = formData.value
        const imageUrls = extractImageUrls(formData.value.introduce)
        if(imageUrls.length > 0){
        adminDelTag({ img: imageUrls })
      }
      }
      
      http(params)
        .then((res) => {
          if (res.errorCode) {
            message.error(res.msg)
            return
          }
          showAddDialog.value = false
          emits('success')
          formData.value = {
            prize_name: '',
            prize_image: '',
            stock: '',
            probability: '',
            introduce: ''
          }
        })
        .catch((err) => {})
        .finally(() => {
          loading.value = false
        })
    })
  }

  const handleCancel = () => {
    showAddDialog.value = false
    emits('close') // Close the dialog
  }
  const dateRow = ref()
  const richImage = ref(null)
  const maxCanUse = ref(0)
  const paginationTotal = ref(0)
  const init = (canUse, total, row) => {
    showAddDialog.value = true
    nextTick(() => {
      formRef.value.resetFields()

      maxCanUse.value = canUse.toFixed(2)
      paginationTotal.value = total
      if (row) {
        let data = JSON.parse(JSON.stringify(row))
        dateRow.value = JSON.parse(JSON.stringify(row))
        formData.value = {
          prize_name: data.prize_name,
          prize_image: data.prize_image,
          stock: data.stock,
          probability: data.probability,
          introduce: data.introduce,
          raffle_id: data.raffle_id
        }
        richImage.value = extractImageUrls(row.introduce)
      }
    })
    //
  }
  defineExpose({
    init
  })
</script>

<style scoped></style>
